const peers = {} // The session information of each peer is stored

let clientSocket
export const setClientSocket = (socket) => {
  clientSocket = socket
  console.log('Socket ready')
}

// Get the ICE server configuration
export const getIceServers = async () => {
  try {
    const response = new Promise((resolve) => {
      clientSocket.emit('getIceServersRequest')
      console.log('getIceServersRequest sent')
      clientSocket.on('getIceServersResponse', (response) => resolve(response))
    })
    return response
  } catch (error) {
    console.error('Error fetching ICE servers:', error)
    throw new Error('Failed to fetch ICE servers. Please try again later.')
  }
}

// Send offer and get answer
export const handleCall = async (peerId, url, offer) => {
  try {
    const response = new Promise((resolve) => {
      clientSocket.emit('callRequest', url, offer)
      peers[peerId] = peers[peerId] || {}
      peers[peerId].offer = offer
      clientSocket.on('callResponse', (response) => {
        peers[peerId].answer = response
        resolve(response)
      })
    })
    return response
  } catch (error) {
    console.error(`Error handling call for peer ${peerId}:`, error)
    throw new Error('Failed to handle call. Please try again later.')
  }
}

// Create an offer
export const createOffer = async (peerId, url) => {
  try {
    const response = new Promise((resolve) => {
      clientSocket.emit('createOfferRequest', url)
      clientSocket.on('createOfferResponse', (response) => {
        peers[peerId] = peers[peerId] || {}
        peers[peerId].offer = response
        resolve(response)
      })
    })
    return response
  } catch (error) {
    console.error(`Error creating offer for peer ${peerId}:`, error)
    throw new Error('Failed to create offer. Please try again later.')
  }
}

// Set an answer
export const setAnswer = async (peerId, url, answer) => {
  try {
    const response = new Promise((resolve) => {
      clientSocket.emit('setAnswerRequest', url, answer)
      peers[peerId] = peers[peerId] || {}
      peers[peerId].answer = answer
      clientSocket.on('setAnswerResponse', (response) => resolve(response))
    })
    return response
  } catch (error) {
    console.error(`Error setting answer for peer ${peerId}:`, error)
    throw new Error('Failed to set answer. Please try again later.')
  }
}

// Close the call
export const handleCloseCall = async (url) => {
  try {
    const response = new Promise((resolve) => {
      clientSocket.emit('hangupRequest', url)
      clientSocket.on('hangupResponse', (response) => resolve(response))
    })
    return response
  } catch (error) {
    console.error(`Error close the call:`, error)
    throw new Error('Failed to close the call. Please try again later.')
  }
}

// Add ICE candidates
export const addIceCandidate = async (url, candidate) => {
  try {
    const response = new Promise((resolve) => {
      clientSocket.emit('addIceCandidateRequest', url, candidate)
      
      clientSocket.on('addIceCandidateResponse', (response) => {
        resolve(response)
        // 移除监听器
        clientSocket.removeAllListeners('addIceCandidateResponse')
      })
    })
    return response
  } catch (error) {
    console.error('Error adding ICE candidate:', error)
    throw new Error('Failed to add ICE candidate. Please try again later.')
  }
}

// Get a list of ICE candidates
export const getIceCandidate = async (peerId, url) => {
  try {
    const response = new Promise((resolve) => {
      clientSocket.emit('getIceCandidateRequest', url)
      clientSocket.on('getIceCandidateResponse', (response) => {
        peers[peerId] = peers[peerId] || {}
        peers[peerId].iceCandidates = peers[peerId].iceCandidates || []
        peers[peerId].iceCandidates.push(...response)
        resolve(response)
      })
    })
    return response
  } catch (error) {
    console.error(`Error getting ICE candidates for peer ${peerId}:`, error)
    throw new Error('Failed to get ICE candidates. Please try again later.')
  }
}
